<template>
  <!-- 添加品牌的按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="showDialog">添 加</el-button>
  </div>
  <!--  添加或修改品牌的对话框-->
  <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
    <el-form label-width="120px">
      <el-form-item label="品牌名称">
        <el-input v-model="brand.name"/>
      </el-form-item>
      <el-form-item label="品牌图标">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8501/admin/system/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
        >
          <img v-if="brand.logo" :src="brand.logo" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--展示数据的表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="name" label="品牌名称"/>
    <el-table-column prop="logo" label="品牌图标" #default="scope">
      <img :src="scope.row.logo" width="50"/>
    </el-table-column>
    <!--    <el-table-column prop="createTime" label="创建时间" />-->
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="showEdit(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="deleteById(scope.row.id)" >
        删除
      </el-button>
    </el-table-column>
  </el-table>
  <!--分页条-->
  <el-pagination
      :page-sizes="[2,5,510, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      v-model:current-page="pageParams.currentPage"
      v-model:page-size="pageParams.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

</template>

<script setup>
import {ref, onMounted} from 'vue'
import {getBrandByPage, savaBrand,editBrand,deleteBrandById} from "@/api/brand"
import {ElMessage, ElMessageBox} from "element-plus";
import {useApp} from "@/pinia/modules/app";
// 删除品牌
const deleteById=id=>{
  //提示用户是否真的要删除
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async ()=>{
      //删除
      const {code}=await  deleteBrandById(id)
      if(code === 200){
        ElMessage.success("删除成功")
        fetchData()
      }
  }).catch(()=>{
    ElMessage.info("取消删除")
  })
}
// 访问带的token
const headers = ref({
  token: useApp().authorization.token
})
// logo上传成功的回掉函数
const handleAvatarSuccess = (resp) => {
  //resp 是我们后端返回的数据
  //可以用解构表达式拿, 也可以直接通过.的方式拿
  brand.value.logo = resp.data   //拿到了,后端返回的logo的url

}
// 修改
const showEdit=row=>{
  //回显数据
  brand.value=row
  //显示新增对话框
  dialogVisible.value=true
  // console.log(row)
}
//对修改方法进行封装
const edit= async ()=>{
 const {code} = await  editBrand(brand.value)
  if(code===200){
    ElMessage.success("修改成功")
    //关闭对话框
    dialogVisible.value=false
    //刷新数据
    fetchData();
  }
}
//添加或更新的提交按钮
const saveOrUpdate = () => {
  if (brand.value.id) {
    edit()
    //有id说明是修改
  } else {
    //没有id说明是新增
    sava()
  }


}
// 新增品牌方法封装
const sava = async () => {
  const {code} = await savaBrand(brand.value)
  if (code === 200) {
    ElMessage.success("新增成功")
    // 关闭对话框
    dialogVisible.value = false
    //刷新数据
    fetchData()
  }
}
//  显示对话框
// 定义提交表单数据模型
const defaultForm = {
  id: '',
  name: '',
  logo: ""
}
const brand = ref(defaultForm)
const showDialog = (id) => {
  //清空无用的数据, 防止对用户产生干扰
  brand.value = {}
  console.log(id)
  dialogVisible.value = true
}
//  对话框显示的数据模型

//  控制添加对话框是否可见
const dialogVisible = ref(false)
// 分页每页大小发生改变
const handleSizeChange = () => {
  // console.log(limit)
  // pageParams.value.pageSize=limit
  fetchData()
}
//分页 页数发生改变
const handleCurrentChange = () => {
  // console.log(page)
  // pageParams.value.currentPage=page
  fetchData()

}
// 定义表格数据模型
const list = ref([])
// 定义分页查询模型
const pageParams = ref({
  currentPage: 1,
  pageSize: 2
})
onMounted(() => {
  //挂载后直接查询
  fetchData()
})
const fetchData = async () => {
  const {data} = await getBrandByPage(pageParams.value.currentPage, pageParams.value.pageSize)
  //列表的数据
  list.value = data.list;
  //总条数
  total.value = data.total;
}


// ================数据模型定义  start ===============================================
// 定义搜索表单数据模型
const brandList = ref([
  {
    "id": 2,
    "createTime": "2023-05-06 09:31:19",
    "name": "华为",
    "logo": "http://139.198.127.41:9000/sph/20230506/华为.png"
  },
  {
    "id": 1,
    "createTime": "2023-05-06 09:30:27",
    "name": "小米",
    "logo": "http://139.198.127.41:9000/sph/20230506/小米.png"
  }
])

const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  lazyLoad(node, resolve) {   // 加载数据的方法
    const data = [
      {
        "id": 643,
        "createTime": "2023-05-22 15:31:18",
        "name": "玩具乐器",
        "imageUrl": "https://lilishop-oss.oss-cn-beijing.aliyuncs.com/0f423fb60f084b2caade164fae25a9a0.png",
        "parentId": 0,
        "status": 1,
        "orderNum": 10,
        "hasChildren": true,
        "children": null
      },
      {
        "id": 576,
        "createTime": "2023-05-22 15:31:13",
        "name": "汽车用品",
        "imageUrl": "https://lilishop-oss.oss-cn-beijing.aliyuncs.com/665dd952b54e4911b99b5e1eba4b164f.png",
        "parentId": 0,
        "status": 1,
        "orderNum": 10,
        "hasChildren": true,
        "children": null
      },
    ]
    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)


// 分页条数据模型
const total = ref(0)

//======   数据模型定义end========================================================
</script>
<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>